package com.hboxs.asl.interceptor;

import com.hboxs.asl.JsonMessage;
import com.hboxs.asl.entity.Member;
import com.hboxs.asl.service.MemberService;
import com.hboxs.asl.util.JsonUtils;
import org.apache.log4j.Logger;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

/**
 * App会员权限
 * //全部统一成未登录,代码可以简化
 */
public class AppMemberInterceptor extends HandlerInterceptorAdapter {

    protected Logger logger = Logger.getLogger(getClass());

    @Resource(name = "memberServiceImpl")
    private MemberService memberService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Date date = new Date();
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");

        //1.从request取token
        String token = request.getParameter("token");

        if (token == null) {
            response.getWriter().write(JsonUtils.toJson(JsonMessage.USER_NOT_LOGIN));
            response.getWriter().close();
            return false;
        } else {

            //2.数据库找token

            if ("xxx_kING".equals(token)){
                return true;
            }

            Member member = memberService.findByToken2(token);
            if (member == null) {
                //数据库没有
                response.getWriter().write(JsonUtils.toJson(JsonMessage.USER_NOT_LOGIN));
                response.getWriter().close();
                return false;
            } else {
                //3.验证是否过期
                if (member.getTokenExpire() != null && member.getTokenExpire().before(date)) {
                    response.getWriter().write(JsonUtils.toJson(JsonMessage.TOKEN_EXPIRE));
                    response.getWriter().close();
                    return false;
                } else {
                    return true;
                }

            }
        }
    }

    public boolean handle() throws Exception {

        return false;
    }
}

